// Date Range Vtypes
Ext.apply(Ext.form.VTypes, {
    daterange: function(val, field){
        var date = field.parseDate(val);
        
        if (!date) {
            return false;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            start.validate();
            this.dateRangeMax = date;
        }
        else 
            if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
                var end = Ext.getCmp(field.endDateField);
                end.setMinValue(date);
                end.validate();
                this.dateRangeMin = date;
            }
        /*
         * Always return true since we're only using this vtype to set the
         * min/max allowed values (these are tested for after the vtype test)
         */
        return true;
    }
});

Ext.ns('App', 'App.control');
App.control.editForm = Ext.extend(Ext.FormPanel, {
    // Prototype Defaults, can be overridden by user's config object
    labelAlign: 'right',
    frame: true,
    mapWin: null,
    oldvalues: null,
    url: '/test',
    //title: 'Construction Impact Form',
    bodyStyle: 'padding:5px 5px 0',
    //    width: 650,
    autoScroll: true,
    //create a new entry
    new_entry: function(){
        this.getForm().reset();
        this.setTitle('New Impact');
        this.loadMapControl(null);
    },
    reader: new Ext.data.JsonReader({
        root: 'record',
        fields: ['project', {
            name: 'start_date',
            type: 'date',
            dateFormat: 'm/d/Y'
        }, {
            name: 'end_date',
            type: 'date',
            dateFormat: 'm/d/Y'
        }, 'projectid', 'pm']
    }),
    /*
     * build the ui of the buttons at the bottom
     */
    buildButtons: function(){
        return [{
            text: 'Save',
            handler: this.onSave,
            scope: this
        }, {
            text: 'Cancel',
            handler: this.onCancel,
            scope: this
        }]
    },
    /*
     * Save the record
     */
    onSave: function(btn, e){
        var url = this.url;
        this.getForm().submit({
            clientValidation: true,
            url: url,
            method: 'post',
            params: {
                request_type: 'new'
            },
            
            success: function(form, action){
                Ext.Msg.alert('Success', action.result.msg);
            },
            failure: function(form, action){
				if (action.failureType=='client') {
					Ext.Msg.alert('Form Error', 'Please correct the errors highlighted!');
				} else {
					Ext.Msg.alert('Form Error', action.result.msg);	
				}
                
            }
        });
        
    },
    
    loadRecord: function(data){
        this.oldvalues = data;
        this.getForm().loadRecord(data);
        this.loadMapControl(data);
    },
    loadMapControl: function(data){
        var mCtrl = this.findByType('app_mapcontrol')[0];
        if (data) {
            mCtrl.updateControl(data.data.geometry, [data.data.x, data.data.y])
        }
        else {
            mCtrl.load_mask('Not Available...')
        }
        
    },
    /*
     * edit the polygons
     */
    onCancel: function(btn, e){
        var pid = this.getForm().getValues().projectid;
        if (pid == '') {
            //it is a new record
            this.getForm().reset()
        }
        else {
            //load the original values
            this.getForm().loadRecord(this.oldvalues)
        }
        
    },
    onEditPolygon: function(btn, e){
        var mapWin = this.mapWin;
        if (mapWin) {
            mapWin.show()
            
        }
        else {
            mapWin = new App.control.mapEditor({
                width: 800,
                height: 400
            });
            mapWin.show();
            this.mapWin = mapWin;
        }
        
        mapWin.form = this;
        
        var geom_text = this.getForm().getValues().geometry;
        var mapEditor = Ext.getCmp('app-mappanel');
        mapEditor.load(geom_text, null);
        
        //force redraw
        
        var task = new Ext.util.DelayedTask(function(){
            var mp = mapWin.findByType('mappanel')[0];
            var xy = mp.map.getCenter();
            var polygon;
            if (mp.polygon_layer.features.length == 1) {
                var bounds = mp.polygon_layer.features[0].geometry.getBounds();
                mp.map.zoomToExtent(bounds)
            }
            else {
                mp.map.setCenter(new OpenLayers.LonLat(xy.lon + 0.00001, xy.lat));
            }
            
            
            
        });
        
        task.delay(2000);
        
        
        
        
        
        
    },
    //return the predefined parameters
    buildConfig: function(){
		//add pm dropdown list
		var pmStore =  new Ext.data.JsonStore({
        fields: ['value'],
		root: 'results',
		proxy: new Ext.data.HttpProxy({
			url: 'list?list_name=pm',
			method: 'GET'
		})
        
    	});
		pmStore.load();
		var pmCombo = new Ext.form.ComboBox({
			store: pmStore,
			displayField:'value',
	        typeAhead: true,
	        mode: 'local',
	        forceSelection: true,
	        triggerAction: 'all',
	        emptyText:'Select a PM...',
	        selectOnFocus:true,
			fieldLabel: 'PM',
			name: 'pm'
		});
        return {
            title: 'Editing...',
            lableWidth: 75,
            frame: true,
            
            items: [{
            
                xtype: 'textfield',
                fieldLabel: 'ID',
                name: 'projectid',
                anchor: '95%',
                hidden: true,
                hideLabel: true,
                width: 10
            },  //project information
            {
                xtype: 'fieldset',
                autoHeight: true,
                autoWidth: true,
                
                title: 'Project Information',
                defaults: {
                    width: 300
                },
                
                items: [{
                    xtype: 'textfield',
                    allowBlank: false,
                    fieldLabel: 'Project',
                    
                    hidden: false,
                    id: 'project',
                    name: 'project'
                }, {
                
                    allowBlank: false,
                    hideLabel: false,
                    xtype: 'datefield',
                    fieldLabel: 'Start',
                    width: 100,
                    name: 'start_date',
                    startDateField: 'startdt'
                
                }, {
                
                    layout: 'form',
                    
                    allowBlank: false,
                    xtype: 'datefield',
                    width: 100,
                    fieldLabel: 'End',
                    name: 'end_date',
                    startDateField: 'enddt'
                }, 
//				{
//                    xtype: 'textfield',
//                    allowBlank: false,
//                    fieldLabel: 'PM',
//                    name: 'pm'
//                },
				pmCombo, 
				{
                    allowBlank: false,
                    xtype: 'textfield',
                    fieldLabel: 'Project#',
                    name: 'projectno'
                }]
            }, {
                xtype: 'fieldset',
                width: 400,
                title: 'Impacts',
                items: [{
                    xtype: 'checkbox',
                    boxLabel: 'Sidewalk',
                    name: 'sidewalk',
                    hideLabel: true
                }, {
                    xtype: 'checkbox',
                    boxLabel: 'Roadway',
                    name: 'roadway',
                    hideLabel: true
                }, {
                    xtype: 'checkbox',
                    boxLabel: 'Garage',
                    name: 'garage',
                    hideLabel: true
                }, {
                    xtype: 'checkbox',
                    boxLabel: 'ADA Parking',
                    name: 'adaparking',
                    hideLabel: true
                }]
            }, {
                xtype: 'fieldset',
                title: 'Description',
                width: 550,
                
                items: [{
                    xtype: 'htmleditor',
                    allowBlank: true,
                    name: 'description',
                    hideLabel: true,
                    id: 'app-html-editor',
                    
                    height: 200,
                    width: 520
                }, {
                    // Use the default, automatic layout to distribute the controls evenly
                    // across a single row
                    xtype: 'fieldset',
                    title: 'Review Status (Official Use Only)',
                    autoHeight: true,
                    autoWidth: true,
                    items: [{
                        xtype: 'radiogroup',
                        hideLabel: true,
						id: 'reviewstatus',
                        width: 200,
						//defaultType: 'radio',
                        items: [{
                            boxLabel: 'Public',
                            name: 'reviewstatus',
                            inputValue: 'Public'
                        }, {
                            boxLabel: 'Internal',
                            name: 'reviewstatus',
                            inputValue: 'Private'
                        }]
                    }]
                
                }, {
                xtype: 'fieldset',
                autoHeight: true,
                width: 350,
                title: 'Map',
                collapsible: true,
                collapsed: false,
				buttons: [{
                        handler: this.onEditPolygon,
                        text: 'Edit Impact Polygon',
                        scope: this,
                        minWidth: 300
						
                    }],
                items: [{
                    xtype: 'textfield',
                    allowBlank: true,
                    fieldLabel: 'geometry',
                    autoHeight: true,
                    autoWidth: true,
                    hidden: false,
                    id: 'geometry',
                    name: 'geometry',
					hideLabel: true,
					hidden: true
                }, {
                    xtype: 'numberfield',
                    allowBlank: true,
                    fieldLabel: 'x',
                    width: 400,
                    hidden: true,
                    id: 'x',
                    name: 'x',
					hideLabel: true,
					hidden: true
                }, {
                    xtype: 'numberfield',
                    allowBlank: true,
                    fieldLabel: 'y',
                    width: 400,
                    hidden: false,
                    id: 'y',
                    name: 'y',
					hideLabel: true,
					hidden: true
                },
				{
                    xtype: 'app_mapcontrol',
                    
                    width: 350,
                    height: 200,
                    id: 'app-map-control'
                }]
            }]
            
            
            
            
            
            }]
        };
    },
    initComponent: function(){
        // Called during component initialization
        
        // Config object has already been applied to 'this' so properties can 
        // be overriden here or new properties (e.g. items, tools, buttons) 
        // can be added, eg:
        /*
         Ext.apply(this, {
         propA: 3
         });*/
        // Before parent code
        //items has to be add here, because otherwise it will messup the FormPanel.items property
        var config = this.buildConfig();
        
        Ext.apply(this, Ext.apply(this.initialConfig, config));
        this.buttons = this.buildButtons();
        // Call parent (required)
        App.control.editForm.superclass.initComponent.apply(this, arguments);
        
        // After parent code
        // e.g. install event handlers on rendered component
    },
    
    // Override other inherited methods 
    onRender: function(){
    
        // Before parent code
        
        // Call parent (required)
        App.control.editForm.superclass.onRender.apply(this, arguments);
        // After parent code
    
    
    }
});

// register xtype to allow for lazy initialization
Ext.reg('app_editform', App.control.editForm);
